import {useEffect, useMemo, useRef, useState} from 'react';
import {Button, Card, Col, Flex, Form, FormProps, InputNumber, List, Row, Select, Statistic} from 'antd';
import {predict} from "./utils/http.ts";
import {ArrowDownOutlined, ArrowRightOutlined, ArrowUpOutlined} from "@ant-design/icons";
import useApp from "antd/es/app/useApp";
import * as echarts from 'echarts';
import dayjs from "dayjs";

interface PredictionData {
    history: [[Date, number]];
    history_predict: [[Date, number]];
    future_predict: [[Date, number]];
    all_time: [Date];
    steps: number;
}

const Predict = ({cities, attributes, setCurrentCity}: any) => {

        const [loading, setLoading] = useState<boolean>(false);

        const [predictionData, setPredictionData] = useState<PredictionData | null>(null);

        const chartRef = useRef<HTMLDivElement>(null);

        const {message} = useApp()

        useEffect(() => {
            const times = predictionData?.all_time.map(value => (dayjs(value).format('YYYY-MM-DD')));
            const historyValues = predictionData?.history.map(value => (value[1]))
            const historyPredictValues = predictionData?.history_predict.map(value => (value[1]))
            const futurePredictValues = predictionData?.future_predict.map(value => (value[1]))

            const fillCount = predictionData ? historyValues!.length - historyPredictValues!.length : 0;
            const paddedHistoryPredictValues = predictionData ? (fillCount > 0
                ? [...Array(fillCount).fill(null), ...historyPredictValues!]
                : historyPredictValues) : null

            const paddedFuturePredictValues = predictionData ? [...Array(predictionData?.history.length).fill(null), ...futurePredictValues!] : null



            const myChart = echarts.init(chartRef.current);
            const option = {
                title: {
                    text: '趋势预测'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['历史', '历史预测', '未来预测']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: times
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '历史',
                        type: 'line',
                        data: historyValues
                    },
                    {
                        name: '历史预测',
                        type: 'line',
                        data: paddedHistoryPredictValues
                    },
                    {
                        name: '未来预测',
                        type: 'line',
                        data: paddedFuturePredictValues
                    }
                ]
            };
            myChart.setOption(option);
            return () => {
                myChart.dispose();
            }
        }, [predictionData]);

        const getListData = useMemo(() => {
            if (!predictionData) return []
            const history = predictionData.history?.map(value => ({"label": dayjs(value[0]).format('YYYY-MM-DD'), value: value[1]}));
            return [...history]
        }, [predictionData]);


        type FieldType = {
            cityName?: string;
            attribute?: string;
            step?: number;
        };

        const latestTrend = useMemo(() => {
            if (!predictionData) return "暂无数据"
            if (predictionData.future_predict[predictionData?.future_predict.length - 1][1] > predictionData.history[predictionData.history.length - 1][1] * 1.05) {
                return '上升'
            } else if (predictionData.future_predict[predictionData?.future_predict.length - 1][1] < predictionData.history[predictionData.history.length - 1][1] * 0.95) {
                return '下降'
            }
            return '稳定';
        }, [predictionData]);

        const lastestTrendIcon = useMemo(() => {
            if (!predictionData) return null;
            if (predictionData.future_predict[predictionData?.future_predict.length - 1][1] > predictionData.history[predictionData.history.length - 1][1] * 1.05) {
                return <ArrowUpOutlined/>;
            } else if (predictionData.future_predict[predictionData?.future_predict.length - 1][1] < predictionData.history[predictionData.history.length - 1][1] * 0.95) {
                return <ArrowDownOutlined/>
            }
            return <ArrowRightOutlined/>
        }, [predictionData]);

        const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
            message.success("提交成功")
            setLoading(true);
            if (values.cityName && values.attribute && values.step) {
                try {
                    const res = await predict(values.cityName, values.attribute, values.step);
                    setPredictionData(res as any);
                    message.success("预测成功")
                } catch (error) {
                    message.error("服务器异常");
                    setLoading(false);
                }
            }

            setLoading(false);
        };

        const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
            console.log('Failed:', errorInfo);
            setLoading(false);
        };


        return (
            <Flex style={{flexDirection: 'column', margin: "10px", overflow: "hidden"}} gap={"middle"}>
                <Card>
                    <Form
                        name="basic"
                        labelCol={{span: 2}}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >

                        <Form.Item<FieldType>
                            label="城市"
                            name="cityName"
                            rules={[{required: true, message: '请选择城市'}]}
                        >
                            <Select
                                onSelect={(value: string) => {
                                    setCurrentCity(value);
                                }}
                                options={cities}
                            />
                        </Form.Item>

                        <Form.Item<FieldType>
                            label="属性"
                            name="attribute"
                            rules={[{required: true, message: '请选择属性'}]}
                        >
                            <Select
                                options={attributes}
                            />
                        </Form.Item>

                        <Form.Item<FieldType>
                            label="预测步数"
                            name="step"
                            initialValue={12}
                            rules={[{required: true}]}
                        >
                            <InputNumber min={1} max={500} onChange={(value) => {
                                console.log('changed', value);
                            }}/>
                        </Form.Item>


                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit" loading={loading}>
                                开始预测
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>
                <Card>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Statistic
                                title="历史数据点数"
                                value={predictionData ? predictionData.history.length : "暂无数据"}
                            />
                        </Col>
                        <Col span={12}>
                            <Statistic
                                title="预测步数"
                                value={predictionData ? predictionData.steps : "暂无数据"}
                            />
                        </Col>
                    </Row>
                    <Row gutter={16} style={{marginTop: '50px'}}>
                        <Col span={12}>
                            <Statistic
                                title="最新数值"
                                value={predictionData ? predictionData.history[predictionData.history.length - 1][1] : "暂无数据"}
                                precision={4}
                            />
                        </Col>
                        <Col span={12}>
                            <Statistic
                                title="预测趋势"
                                value={latestTrend}
                                valueStyle={{color: predictionData ? (latestTrend == '下降' ? '#bd1818' : '#3f8600') : 'black'}}
                                prefix={lastestTrendIcon}
                            />
                        </Col>
                    </Row>
                </Card>
                <Card>
                    <div ref={chartRef} style={{height: "500px", width: "100%"}}></div>
                </Card>
                <Card>
                    <List
                        itemLayout="horizontal"
                        dataSource={getListData}
                        renderItem={(item) => (
                            <List.Item>
                                <List.Item.Meta
                                    title={item.label}
                                />
                                <div>{item.value}</div>
                            </List.Item>
                        )}
                    />
                </Card>

            </Flex>

        );
    }
;

export default Predict;
